package com.g2.rpc.remoting.netty;

import com.g2.rpc.remoting.Codec;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import org.apache.log4j.Logger;

import java.util.List;

/**
 * 描述:
 * ${DESCRIPTION}
 *
 * @author lingjiu.kong
 * @version 1.0
 * @date 2021-03-05 22:04
 */
public class NettyCodec extends ChannelDuplexHandler {

    private static Logger log = Logger.getLogger("g2rpc");


    private Codec codec;

    public NettyCodec(Codec codec) {
        this.codec = codec;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf byteBuf = (ByteBuf) msg;
        byte[] array = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(array);
        List<Object> objs = codec.decode(array);
        log.info("解析到:" + objs.size() + "条数据");
        for (Object o : objs) {
            ctx.fireChannelRead(o);
        }
    }

    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
        byte[] encode = codec.encode(msg);
        super.write(ctx, Unpooled.wrappedBuffer(encode), promise);
    }
}
